package com.liziyi0914.morearmor.effect;

import com.liziyi0914.morearmor.PlayerManager;
import com.liziyi0914.morearmor.Utils;
import com.liziyi0914.morearmor.event.Listener;
import com.liziyi0914.morearmor.event.entity.EntityInteractEntityEvent;
import com.liziyi0914.morearmor.event.entity.WorldTickEvent;
import net.minecraft.entity.Entity;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.Items;
import net.minecraft.server.network.ServerPlayerEntity;

import java.util.function.Predicate;

/**
 * 2021/6/30<br>
 * MoreArmor<br>
 *
 * @author huanmeng_qwq
 */
public class SaddleEffect extends AbstractEffect {
    @Listener
    public void onTick(WorldTickEvent e) {
        for (Entity entity : e.getWorld().getEntities()) {
            if (entity instanceof LivingEntity) {
                PlayerEntity playerEntity = PlayerManager.get(entity.getUuid());
                if (playerEntity == null) {
                    return;
                }
                if (!predicateArmor().test(playerEntity)) {
                    if (playerEntity.getFirstPassenger() instanceof LivingEntity) {
                        playerEntity.removeAllPassengers();
                    }
                    return;
                }
            }
        }
    }

    @Listener
    public void onClickEntity(EntityInteractEntityEvent e) {
        if (e.getTarget() == null) return;
        if (!(e.getTarget() instanceof ServerPlayerEntity)) {
            return;
        }
        if (!predicateArmor().test(e.getTarget())) {
            return;
        }
        if (e.getTarget().hasPassengers()) return;
        e.getTarget().startRiding(e.getEntity());
    }

    @Override
    public Predicate<LivingEntity> predicateArmor() {
        return Utils.hasItemArmor(Items.SADDLE);
    }
}
